<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { getCategories, getProductsByCategoryId, getProductsBySubCategoryId } from '@/apis/product.js';
import { useProductsStore } from '@/stores/products';
import { storeToRefs } from 'pinia';

const productsStore = useProductsStore();
const { products } = storeToRefs(productsStore);
const categories = ref([]);
const activeCategoryId = ref(null);
const loading = ref(false);
const allLoaded = ref(false);

// 获取分类数据
onMounted(async () => {
  try {
    const res = await getCategories();
    categories.value = res;
  } catch (error) {
    console.error('Error fetching categories:', error);
  }
});

// 分类点击事件
const handleCategoryClick = async (categoryId) => {
  // 清空商品列表和加载状态
  productsStore.setProducts([]);
  allLoaded.value = false;
  loading.value = false;

  // 根据分类ID重新加载商品数据
  try {
    const res = await getProductsByCategoryId(categoryId); // 获取该分类的商品
    if (res.records.length > 0) {
      productsStore.setProducts(res.records); // 设置新分类的商品数据
      productsStore.setPage(res.total, res.size, 1); // 更新分页信息
    } else {
      allLoaded.value = true; // 如果该分类没有商品，标记已加载完
    }
  } catch (error) {
    console.error('Error fetching products by category:', error);
  }
};

// 子分类点击事件
const handleSubcategoryClick = async (subcategoryId) => {
  // 清空商品列表和加载状态
  productsStore.setProducts([]);
  allLoaded.value = false;
  loading.value = false;

  // 根据子分类ID重新加载商品数据
  try {
    const res = await getProductsBySubCategoryId(subcategoryId); // 获取该子分类的商品
    if (res.records.length > 0) {
      productsStore.setProducts(res.records); // 设置子分类的商品数据
      productsStore.setPage(res.total, res.size, 1); // 更新分页信息
    } else {
      allLoaded.value = true; // 如果该子分类没有商品，标记已加载完
    }
  } catch (error) {
    console.error('Error fetching products by subcategory:', error);
  }
};

// 处理滚动事件，加载更多商品
const handleScroll = async (event) => {
  const bottom = event.target.scrollHeight === event.target.scrollTop + event.target.clientHeight;
  if (bottom && !loading.value && !allLoaded.value) {
    loading.value = true;
    const newPage = products.current + 1;
    try {
      const res = await getProductsByCategoryId(products.currentCategory, newPage, 8); // 根据当前分类请求商品数据
      if (res.records.length > 0) {
        productsStore.setProducts([...products.list, ...res.records]); // 拼接新数据
        productsStore.setPage(res.total, res.size, newPage); // 更新分页信息
      } else {
        allLoaded.value = true; // 标记商品已加载完
      }
    } catch (error) {
      console.error('Error fetching products list:', error);
    } finally {
      loading.value = false;
    }
  }
};

// 确保页面顶部滚动
const resetScroll = () => {
  nextTick(() => {
    const container = document.querySelector('.products-container');
    container.scrollTop = 0;
  });
};

</script>

<template>
  <div class="products-new">
    <h3 class="products-new-title">商品列表</h3>
    <div class="category-list">
      <!-- 假设你有一个分类列表 -->
      <button v-for="category in categories" :key="category.id" @click="handleCategoryClick(category.id); resetScroll()">
        {{ category.name }}
      </button>
    </div>
    <div class="products-container">
      <div class="product-empty" v-if="products.list.length === 0">
        <el-empty description="没有找到相关宝贝"></el-empty>
      </div>
      <div class="product" v-else v-for="product in products.list" :key="product.id">
        <router-link :to="'/product/' + product.id" class="product-link">
          <figure class="product-figure">
            <img :src="'/api/images/' + product.mainImage" alt="图片" />
            <figcaption class="product-title">
              {{ product.name }}
            </figcaption>
            <p class="product-price">
              {{ product.price }}元
            </p>
            <p class="product-subtitle">{{ product.subTitle }}</p>
          </figure>
        </router-link>
      </div>
      <div v-if="allLoaded" class="end-message">已到底</div>
    </div>
  </div>
</template>



<style scoped lang="scss">
.products-new {
  width: 90%;
  margin: 0 auto;
  padding: 2rem 0;
  border-radius: 2rem;
  background-color: #fff;

  .products-new-title {
    font-size: 2rem;
    font-weight: bold;
    margin-bottom: 2rem;
    margin-left: 2rem;
    font-family: PingFang SC, Microsoft YaHei, sans-serif;
  }

  .category-list {
    margin-bottom: 2rem; /* 分类按钮区域的底部间距 */
  }

  /* 修改按钮的样式 */
  .category-list button {
    font-size: 1.2rem; /* 修改按钮字体大小 */
    padding: 0.8rem 1.5rem; /* 修改按钮的内边距，控制按钮的大小 */
    background-color: #f48f5b; /* 按钮背景颜色 */
    border: none; /* 去掉按钮的边框 */
    border-radius: 1rem; /* 按钮的圆角 */
    color: white; /* 按钮字体颜色 */
    cursor: pointer; /* 鼠标悬停时显示为指针 */
    margin-right: 1rem; /* 按钮之间的间隔 */
    transition: background-color 0.3s ease; /* 按钮背景色的过渡效果 */
  }

  /* 鼠标悬停时按钮的样式 */
  .category-list button:hover {
    background-color: #ff6700; /* 鼠标悬停时按钮背景颜色 */
  }

  .products-container {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-column-gap: 1rem;
    width: 100%;
    overflow-y: auto;
    height: 70vh; /* 设置一个高度，限制显示区域 */

    .product-empty {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      grid-column: 1 / -1;
    }

    .product {
      flex: 1;
      display: inline-block;
      width: 19rem;
      margin-left: 1rem;
      text-align: center;

      .product-figure {
        height: 20rem;

        .product-title {
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          font-size: 1.2rem;
          margin-top: 1rem;
        }

        .product-price {
          color: #ff6700;
          font-size: 1.4rem;
          margin-top: 1rem;
        }
      }

      img {
        width: 10rem;
        height: 12rem;
      }

      span {
        color: #cdcdcd;
        text-decoration: line-through;
      }

      a {
        display: inline-block;
        width: 100%;
        height: 50%;
        border: 1px solid rgba(255, 255, 255, 0.5);
        border-radius: 1rem;
        padding: 1rem;
        box-sizing: border-box;
        &:hover {
          cursor: pointer;
          border: 1px solid #ff6700;
          border-radius: 1rem;
        }
      }
    }
  }

  .end-message {
    width: 100%;
    text-align: center;
    padding: 1rem;
    color: #aaa;
    font-size: 1.2rem;
  }
}
</style>
